﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using WhsFacebook.Net.Contracts;

namespace WhsFacebook.Whs.Service.Submitters
{
    public sealed class AddinsSubmitter : InfoSubmitter<IEnumerable<WhsAddinInfo>>
    {
        #region instance

        public static AddinsSubmitter Instance
        {
            get; private set;
        }

        static AddinsSubmitter()
        {
            Instance = new AddinsSubmitter();
        }

        #endregion

        protected override IEnumerable<WhsAddinInfo> DoSubmitInternal()
        {
            // gather add-in list
            var r = new List<WhsAddinInfo>();
            var regBase = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows Home Server\RegisteredAdditions");

            foreach (var sk in regBase.GetSubKeyNames())
            {
                try
                {
                    var skReg = regBase.OpenSubKey(sk);

                    var ai = new WhsAddinInfo()
                    {
                        ProductCode = new Guid(sk),
                        Author = Convert.ToString(skReg.GetValue("Manufacturer")),
                        Title = Convert.ToString(skReg.GetValue("Title")),
                        Version = Convert.ToString(skReg.GetValue("Version")),
                    };

                    r.Add(ai);
                }
                catch (Exception x)
                {
                    if (_log.IsWarnEnabled)
                        _log.Warn("Failed to parse add-in info from registry sub-key: " + sk, x);
                }
            }

            // submit
            using (var wc = new WhsFacebookServiceClientFactory())
            {
                wc.CreateChannel().UpdateInstalledAddins(WhsFacebookRegistry.GetInstanceId(), r);
            }

            return r;
        }

        private AddinsSubmitter()
        {
            
        }
    }
}
